package com.apkfuns.jsbridge.module;


import com.apkfuns.jsbridge.ResourceTable;
import com.apkfuns.jsbridge.util.TakePhotoResult;
import com.apkfuns.jsbridge.util.WebEvent;
import com.apkfuns.jsbridge.view.base.BaseAbility;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.location.Location;
import ohos.location.LocatorCallback;
import ohos.media.image.PixelMap;
import ohos.media.image.common.Size;

import java.nio.ByteBuffer;
import java.util.Base64;


public class NativeModule extends JsModule {
    @Override
    public String getModuleName() {
        return "native";
    }

    @JSBridgeMethod
    public boolean setMenu(String title, final JBCallback callback) {
        if (getContext() != null && getContext() instanceof BaseAbility) {
            ((BaseAbility) getContext()).setMenu(title, new Runnable() {
                @Override
                public void run() {

                    callback.apply(System.currentTimeMillis());
                }
            });

        }
        return false;
    }

    @JSBridgeMethod
    public void alertDialog(String title, String msg, final JBCallback sure, final JBCallback cancel) {

        CommonDialog commonDialog = new   CommonDialog(getContext());

        Component component =   LayoutScatter.getInstance(getContext())

                .parse(ResourceTable.Layout_dialog_custom_layout,   null, true);

        commonDialog.setSize(DirectionalLayout.LayoutConfig.MATCH_CONTENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT);
        commonDialog.setAlignment(LayoutAlignment.CENTER);
        commonDialog.setContentCustomComponent(component);

        commonDialog.show();
        commonDialog.setTitleText(title);
        commonDialog.setContentText(msg);
        Text titleText = (Text) component.findComponentById(ResourceTable.Id_title_text);
        titleText.setText(title);
        Text contentText = (Text) component.findComponentById(ResourceTable.Id_content_text);
        contentText.setText(msg);
        Button  cancelButton  = (Button) component.findComponentById(ResourceTable.Id_cancel_button);
        cancelButton.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                cancel.apply();
                commonDialog.hide();
                commonDialog.destroy();
            }
        });

        Button sureButton  = (Button) component.findComponentById(ResourceTable.Id_sure_button);
        sureButton.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                sure.apply();
                commonDialog.hide();
                commonDialog.destroy();
            }
        });
    }

    @JSBridgeMethod
    public void getLocation(final JBCallback callback, final JBCallback change) {

        if (getContext() != null && getContext() instanceof BaseAbility) {
            Location location =   ((BaseAbility) getContext()).getLocation(new LocatorCallback() {
                @Override
                public void onLocationReport(Location location) {
                    change.apply(location.getLatitude(), location.getLongitude());
                }

                @Override
                public void onStatusChanged(int i) {

                }

                @Override
                public void onErrorReport(int i) {

                }
            });

            if (location != null) {
                callback.apply(location.getLatitude(), location.getLongitude());
            } else {
                callback.apply();
            }
        }
    }

    @JSBridgeMethod
    public void loadNewPage(String url) {

        Intent it = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName(getContext().getBundleName())
                .withAbilityName("com.apkfuns.jsbridge.view.WebViewAbility")
                .build();

        it.setOperation(operation);
        it.setParam("url", url);
        getContext().startAbility(it,0);
    }

    @JSBridgeMethod
    public void takePhoto(final JBCallback success, final JBCallback errorCallback) {

        if (getContext() != null) {
            WebEvent webEvent = null;
            if (getContext() instanceof WebEvent) {
                webEvent = (WebEvent) getContext();
            }

            if (webEvent == null) {
                return;
            }
            webEvent.takePhoto(new TakePhotoResult() {

                @Override
                public void onSuccess(PixelMap bitmap) {
                    // 传输的最大数据 200w 字符左右，最大图片1.47M 左右
                    if (bitmap != null) {
                        if (success != null) {
                            String base64 = bitmapToBase64(bitmap);
                            base64 = "data:image/png;base64," + base64;
                            success.apply(base64);
                        }
                    } else {
                        if (errorCallback != null) {
                            errorCallback.apply("data error");
                        }
                    }
                }

                @Override
                public void onSuccess(String bitmap) {

                    if (bitmap != null) {
                        if (success != null) {
                            String base64 = "data:image/jpg;base64," + bitmap;

                            success.apply(base64);
                        }
                    } else {
                        if (errorCallback != null) {
                            errorCallback.apply("data error");
                        }
                    }
                }

                @Override
                public void onFailure(String error) {
                    if (errorCallback != null) {
                        errorCallback.apply(error);
                    }
                }
            });
        }
    }


    /**
     * 压缩并 转 base64
     * @param pixelMap
     * @return
     */
    public static String bitmapToBase64(PixelMap pixelMap) {

        String result = null;
        if (pixelMap != null) {
            Size size = pixelMap.getImageInfo().size;
            ByteBuffer byteBuffer = ByteBuffer.allocate(size.width * size.height * 4);
            pixelMap.readPixels(byteBuffer);
            byteBuffer.flip();
            result =  Base64.getEncoder().encodeToString(byteBuffer.array());
        }

        return result;
    }
}
